<?php
namespace App\Admin\Controllers\Quality;

use App\Models\Basics\SysArea;
use App\Models\Basics\SysICountry;
use App\Models\Product\ProductClassify;
use App\Models\Quality\QReportClassify;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ReportClassifyController extends AdminController{

    protected $title = '品类品质报表';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
        'area_id' => null,
        'country_id' => null,
        'classify_id' => null,
        'season' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $_query = clone $query;
        $headers = QReportClassify::headersField();
        $paginator = $this->_paginator($query);
        $total = $this->_sum($_query,$headers);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
        $filtersBlade['area_id'] = getOptions(SysArea::options(),$this->filters['area_id']);
        $filtersBlade['country_id'] = getOptions(SysICountry::options(),$this->filters['country_id']);
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        $filtersBlade['season'] = getOptions(ProductClassify::$_season,$this->filters['season']);
        $downloadUrl = '/xqc/quality/report-c-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        return view('quality.report-c.index', compact('paginator','total','headers','filtersBlade','action','downloadUrl'));
    }

    private function _getFilters($filtersField){
        $startDate = request('start_date');
        $endDate = request('end_date');
        $reportDate = $this->__reportDate($startDate,$endDate);
        $filters = [];
        foreach ($filtersField as $field){
            if(array_key_exists($field,$reportDate)){
                $filters[$field] = $reportDate[$field];
            }else{
                $filters[$field] = request($field);
            }
        }
        return $filters;
    }

    private function __reportDate($start,$end){
        $time = strtotime("midnight first day of -1 month");
        if(is_null($start) && is_null($end)){
            $startDate = $endDate = date('Y-m-01',$time);
        }elseif(!is_null($start) && is_null($end)){
            $startDate = $endDate = $start;
        }elseif(is_null($start) && !is_null($end)){
            $startDate = $endDate = $end;
        }else{
            $startDate = $start;
            $endDate = $end;
        }
        return ['start_date' => $startDate,'end_date' => $endDate];
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = QReportClassify::query();
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'start_date'){
                $query->where('report_date','>=',$filter);
            }
            if($field == 'end_date'){
                $query->where('report_date','<=',$filter);
            }
            if($field == 'season'){
                $query->whereHas('classify', function ($query) use($filter){
                    $query->where('season', $filter);
                });
            }
            if(in_array($field,['area_id','country_id','classify_id'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    private function _sum($query,$headers){
        $sum = $query->selectRaw($this->__getSumFields($headers))->groupBy(1)->first();
        return $sum ? $sum->toArray() : $this->__getSumFieldsInit($headers);
    }

    private function __getSumFields($headers){
        $re = '';
        foreach ($headers as $field => $item){
            if($item['sumField']){
                $re .= 'sum('.$field.') as '.$field.',';
            }else{
                continue;
            }
        }
        return $re.'1';
    }

    private function __getSumFieldsInit($headers){
        $re = [];
        foreach ($headers as $field => $item){
            if($item['sumField']){
                $re[$field] = 0;
            }else{
                continue;
            }
        }
        return $re;
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $query->with(['area','country','classify']);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['日期','站点','国家','季节性','品类', '当月销量',
            '当月退货量','当月退货率','可二次销售量','可二次销售率',
            '尺码问题','尺码问题数量','尺码问题比例',
            '做工问题','做工问题数量','做工问题比例',
            '设计问题','设计问题数量','设计问题比例',
            '主观问题','主观问题数量','主观问题比例',
            '汇总问题'];
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="品类品质报表.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->orderBy('id','DESC')->chunk(800, function ($re) use ($fp){
                $data = QReportClassify::getData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }
}
